import fs from 'fs';
import multer from 'multer';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

var y = new Date().getFullYear()
var m = new Date().getMonth() + 1
var filepath = path.resolve(__dirname, '../../../' ,`uploads\/${y}-${m>9?m:'0'+m}\/`)

// 定义上传限制
const ARRAY_MAX_COUNT = 9
const FILE_TYPE = ['file','txt','pdf','jpg','png','xls','xlsx','word','gif','mp3','mp4','pptx']
const AVATAR = 'file'

var storage = multer.diskStorage({
  destination: (req, file, cb) => {
    fs.mkdirSync(filepath,{recursive: true}, (err) => {
      if (err) throw ('mkdir error:'+err)
    })
    cb(null, filepath)
  },
  filename: (req, file, cb) => {
    // 文件名后缀
    let ext = path.extname(file.originalname) || '.txt'
    // 拼接文件名
    cb(null, file.fieldname + '_' + Date.now() + ext)
  },
})

const fileFilter = (req, file, callback) => {
  // file.originalname = Buffer.from(file.originalname,'latin1').toString('utf8')

  // 控制文件上传字段名
  if (FILE_TYPE.includes(file?.fieldname.toLocaleLowerCase())) callback(null, true)
  else {
    callback(new Error('no support filedname,please use '+FILE_TYPE))
  }
}



/**
 * 多文件上传中间件
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function arrayUpload(req, res, next) {
  const rule = FILE_TYPE.map((e) => {
    return {name:e,maxCount:ARRAY_MAX_COUNT}
  })
  let upload = multer({storage,fileFilter}).fields(rule)
  upload(req, res, (err) => {

    if (err instanceof multer.MulterError) res.send('Upload Error:' + err)
    else if (err) res.send('Server error:' + err)
    else {
      next()
    }
  })
}

function avatarUpload (req, res, next) {
  let upload = multer({storage}).single(AVATAR)
  upload(req, res, (err) => {
    if (err instanceof multer.MulterError) res.send('上传错误:' + err)
    else if (err) res.send('Server error:' + err)
    else {
      next()
    }
  })
}

export {
  arrayUpload,
  avatarUpload
};

